//
//  ZWSeachVC.m
//  WanEr
//
//  Created by 高文萍 on 15/12/27.
//  Copyright © 2015年 高文萍. All rights reserved.
//

#import "ZWSeachVC.h"
#import "WanErHeader.h"
#import "ZWLocationView.h"
#import "ZWSeachModel.h"
#import "ZWSeachTableViewCell.h"
#import <CoreLocation/CoreLocation.h>
@interface ZWSeachVC ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, CLLocationManagerDelegate>

@property (nonatomic, strong) UISearchBar *mainSeach;
@property (nonatomic, strong) UITableView *mainTable;
@property (nonatomic, strong) NSMutableDictionary *searchDic;
@property (nonatomic, strong) NSMutableArray *searchArr;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) ZWLocationView *loclactionView;
@property (nonatomic, copy) NSString *cityStr;
@property (nonatomic, strong) CLLocationManager *locationMg;
@property (nonatomic, copy) NSString *strO;
@property (nonatomic, copy) NSString *strT;
@end

@implementation ZWSeachVC

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.searchDic = [NSMutableDictionary dictionary];
    self.searchArr = [NSMutableArray array];

    [self createLocation];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.mainTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 95, WIDTH, HEIGHT - 95) style:UITableViewStylePlain];
    self.mainTable.delegate = self;
    self.mainTable.dataSource = self;
    self.mainTable.rowHeight = 100;
    [self.view addSubview:self.mainTable];
    
    self.headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 40 + 45)];
    [self.view addSubview:self.headerView];
    self.mainSeach = [[UISearchBar alloc]initWithFrame:CGRectMake(10, 20, WIDTH - 20, 40)];
    self.mainSeach.delegate = self;
    self.mainSeach.searchBarStyle = UIBarStyleBlackTranslucent;
    self.mainSeach.backgroundColor = [UIColor whiteColor];
    self.mainSeach.placeholder = @"搜索城市";
    [self.headerView addSubview:self.mainSeach];
    
    self.loclactionView = (ZWLocationView *)[[[NSBundle mainBundle]loadNibNamed:@"location" owner:self options:nil] lastObject];
    self.loclactionView.frame = CGRectMake(0, 60, WIDTH, 45);
    [self.headerView addSubview:self.loclactionView];
    
    
}
#pragma ---定位---
- (void)createLocation
{
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationMg = [[CLLocationManager alloc] init];
        self.locationMg.delegate = self;
        self.locationMg.desiredAccuracy = kCLLocationAccuracyBest;//控制定位精度,越高耗电量越大。
        self.locationMg.distanceFilter = 10.0f;//控制定位服务更新频率。单位是“米”
        [self.locationMg requestAlwaysAuthorization];
        [self.locationMg startUpdatingLocation];

    }
    //在ios 8.0下要授权
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
        
        [_locationMg requestWhenInUseAuthorization];  //调用了这句,就会弹出允许框了.
    
}
#pragma CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    CLLocation * currLocation = [locations lastObject];
    
//    NSLog(@"%@",[NSString stringWithFormat:@"%.3f",currLocation.coordinate.latitude]);
//    
//    NSLog(@"%@",[NSString stringWithFormat:@"%.3f",currLocation.coordinate.longitude]);
    
        [self.locationMg stopUpdatingLocation];
        NSLog(@"location ok");
    
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark * placemark in placemarks) {
            
            NSDictionary *test = [placemark addressDictionary];
            //  Country(国家)  State(城市)  SubLocality(区)
            self.strO = [NSString stringWithString:test[@"State"]];
            self.strT = [NSString stringWithString:test[@"SubLocality"]];
            self.loclactionView.locaitonLabel.text = [self.strO stringByAppendingString:self.strT];
            NSLog(@"%@", [test objectForKey:@"State"]);
            NSLog(@"%@", [test objectForKey:@"SubLocality"]);
        }
    }];

    
}




- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    
    
    if (![searchBar.text isEqualToString:@""]) {
        
        NSString *str = [[NSString stringWithFormat:@"http://app.ziwoxz.com/agi/scenerie/index/searchval/%@/page/1",searchBar.text] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        [JXRAFNetWorkTool getNetWithURL:str body:nil resultKind:JXRJSON headerFile:nil success:^(id result) {
            
            if ([result[@"data"][@"ids"] count] == 0) {
                
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"暂时无数据哦~" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil];
                [alert show];

                [self.mainTable reloadData];

            }else{
                self.searchDic = result[@"data"][@"main_sceneries"];
                self.searchArr = [ZWSeachModel baseModelByArr:result[@"data"][@"sceneries"] arr:self.searchArr];
                [self.mainTable reloadData];
            }
         
            
        } failure:^(NSError *error) {
            
        }];

        
    }

}
#pragma ---headerSection个数---
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
#pragma ---返回header高度---
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 15;
}
#pragma ---sectionHeaderView创建---
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 0)];
    headV.backgroundColor = [UIColor colorWithWhite:0.786 alpha:1.000];
    self.mainTable.tableHeaderView = headV;
    
    UILabel *seachLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, WIDTH, 15)];
    seachLabel.text = @"最新搜索";
    seachLabel.font = [UIFont systemFontOfSize:12];
    [headV addSubview:seachLabel];
    
    return headV;

}
#pragma ---tableview协议方法---
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        static NSString *reuse = @"reuse";
        ZWSeachTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[ZWSeachTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
        }
        
    // 关键字高亮
//    if (self.mainSeach.text.length != 0) {
//        NSMutableAttributedString *attrituteString = [[NSMutableAttributedString alloc] initWithString:self.searchDic[@"scenerie_name"]];
//        NSRange range = [self.searchDic[@"scenerie_name"] rangeOfString:self.mainSeach.text];
//        [attrituteString setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1.000 green:0.660 blue:0.963 alpha:1.000],   NSFontAttributeName : [UIFont systemFontOfSize:22]} range:range];
//        cell.seachName.attributedText = attrituteString;
//    }else{cell.seachName.text = self.searchDic[@"scenerie_name"];
//        
//    }
//    
//    if (self.mainSeach.text.length != 0) {
//        NSMutableAttributedString *attrituteString = [[NSMutableAttributedString alloc] initWithString:self.searchDic[@"area"]];
//        NSRange range = [self.searchDic[@"area"] rangeOfString:self.mainSeach.text];
//        [attrituteString setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:0.698 green:1.000 blue:0.861 alpha:1.000],   NSFontAttributeName : [UIFont systemFontOfSize:22]} range:range];
//        cell.areaLabel.attributedText = attrituteString;
//    }else{
//        cell.areaLabel.text = self.searchDic[@"area"];
//    }
//    

        cell.seachName.text = self.searchDic[@"scenerie_name"];
        [cell.seachImge sd_setImageWithURL:[NSURL URLWithString:self.searchDic[@"image_url"][0]]];
        cell.areaLabel.text = self.searchDic[@"area"];
        return cell;
        
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
